//======================
//操作mysql数据库的API
//======================
const { QueryTypes } = require('sequelize');

class API {
  //创建数据
  createData(modelName, o, t) {
    //modelName: 模型名称, string
    //o: 创建的数据, object
    //t: 事务处理对象

    //返回promise

    return t ? model[modelName].create(o, { transaction: t }) : model[modelName].create(o);
  }
  
  //创建数据
  createData(modelName, o) {
    //o: 创建的数据, 类型: object

    //返回promise
    return model[modelName].create(o);
  }

  //删除

  //更新
  updateData(modelName, values, condition, t) {
    //modelName: 模型名称, string
    //values: 更新数据, object
    //condition: 条件, object
    //t: 事务处理对象, object
    if (t) {
      return model[modelName].update(values, {
        where: condition,
        transaction: t
      });
    }

    return model[modelName].update(values, {
      where: condition
    });

  }
  //查询
  findData(o) {
    //返回promise
    return model[o.modelName].findAll({
      where: o.where,
      attributes: o.attributes,
      order: o.order,
      limit: o.limit,
      offset: o.offset
    })
  }
  //查询单个数据/外键
  findOne(o) {
    //返回promise
    return model[o.modelName].findAll({
      where: o.where,
      include: [{
        model: model[o.include.modelName],
        where: o.include.where,
        attributes: o.include.attributes
      }],
    })
  }

  //查询单个数据
  findOne2(o) {
    //返回promise
    return model[o.modelName].findAll({
      where: o.where,
    })
  }

  // 分页查询/外键查询
  findCount(o) {
    return model[o.modelName].findAndCountAll({
      where: o.where,
      offset: o.offset * o.limit,
      order: o.order,
      limit: o.limit,
      include: [{
        model: model[o.include.modelName],
        where: o.include.where,
        attributes: o.include.attributes
      }],
      raw: true
    });
  }

  // 分页查询
  findCount2(o) {
    return model[o.modelName].findAndCountAll({
      where: o.where,
      offset: o.offset * o.limit,
      order: o.order,
      limit: o.limit,
    });
  }

  //事务处理
  transaction(fn) {
    return sequelize.transaction(fn);
  }

  //原始查询
  query(sql, replacements) {
    //sql: SQL语句, string
    //replacements: 替换SQL语句的内容, object
    return sequelize.query(sql, {
      replacements,
      type: QueryTypes.SELECT
    })
  }
  //删除
  removeData(modelName, condition, t) {
    //modelName: 模型名称, string
    //condition: 条件, object
    //t: 事务处理对象, object

    if (t) {
      return model[modelName].destroy({
        where: condition,
        transaction: t
      })
    }

    return model[modelName].destroy({
      where: condition
    })
  }
}

module.exports = new API();